use crate::game::error::CustomErr;
use crate::game::init::ensure_data_dir;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use rand::rng;
use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize};
use std::ffi::OsStr;
use std::fs;

#[derive(Serialize, Deserialize, Debug)]
pub struct ImgInfo {
    pub base64_content: String,
    pub name: String,
}

// 获取文件路径
#[tauri::command]
pub fn load_img_base64(dir: String, rand_flag: bool) -> Result<Vec<ImgInfo>, CustomErr> {
    // 获取基础路径
    let base_dir = ensure_data_dir(dir)?;

    // 图片路径数组
    let mut img_vec = Vec::new();

    for entry in fs::read_dir(base_dir)? {
        let entry_content = entry?;
        let path = entry_content.path();
        if path.is_file() {
            //根据文件拓展名过滤
            let filename = path.file_stem().unwrap().to_str().unwrap().to_string();
            if let Some(ext) = path.extension().and_then(OsStr::to_str) {
                if ["jpg", "jpeg", "png", "pdf", "gif"].contains(&ext.to_lowercase().as_str()) {
                    // 3. 根据文件类型生成对应的 MIME 类型
                    let mime_type = match ext.to_lowercase().as_str() {
                        "png" => "image/png",
                        "jpg" | "jpeg" => "image/jpeg",
                        "gif" => "image/gif",
                        "webp" => "image/webp",
                        "txt" => "text/plain",
                        "pdf" => "application/pdf",
                        _ => "application/octet-stream", // 默认类型
                    };

                    // 4. Base64 编码并拼接文件头
                    let file_data = fs::read(path)?;
                    let base64_data = STANDARD.encode(&file_data);
                    let result = format!("data:{};base64,{}", mime_type, base64_data);
                    img_vec.push(ImgInfo {
                        base64_content: result,
                        name: filename,
                    });
                }
            }
        }
    }

    // 随机打乱数组
    if rand_flag {
        img_vec.shuffle(&mut rng());
    }
    Ok(img_vec)
}

// 获取当前目录子文件夹
#[tauri::command]
pub fn get_sub_dir(dir: String) -> Result<Vec<String>, CustomErr> {
    // 如果文件夹不存在就创建
    let dir = ensure_data_dir(dir)?;

    let mut sub_dirs = Vec::new();
    for result in fs::read_dir(dir)? {
        let entry = result?;
        let path = entry.path();
        if path.is_dir() {
            if let Some(dir_name) = path.file_name() {
                sub_dirs.push(dir_name.to_string_lossy().to_string());
            }
        }
    }
    Ok(sub_dirs)
}
